﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace BTServer
{
    public partial class UpdateDevice : Form
    {
        public UpdateDevice()
        {
            InitializeComponent();
            refreshDevices();
        }

        private void refreshDevices()
        {
            MySqlConnection conn = ConnectionPool.checkOutConnection();
            heartdb db = new heartdb(conn);
            var query = from d in db.device select d;
            int i = 0;
            foreach (device q in query)
            {
                i++;
                dataGridView1.Rows.Add(new string[] {i+"", q.DeviceName, q.PairPin, q.CreationDate.ToString(), q.Status, q.id.ToString() });
            }
            ConnectionPool.checkInConnection(conn);
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            DataGridView dataGrid = (DataGridView) sender;
            if (dataGrid.SelectedRows.Count > 0)
            {
                txtCode.Text = dataGrid.SelectedRows[0].Cells[2].Value.ToString();
                txtName.Text = dataGrid.SelectedRows[0].Cells[1].Value.ToString();
                device_id = UInt32.Parse(dataGrid.SelectedRows[0].Cells[5].Value.ToString()) ;
            }
        }

        uint device_id;
        private void button2_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = ConnectionPool.checkOutConnection();
            heartdb db = new heartdb(conn);
            device d = (from dev in db.device where dev.id == device_id select dev).First();
            d.DeviceName = txtName.Text;
            d.PairPin = txtCode.Text;
            db.SubmitChanges();
            refreshDevices();
            ConnectionPool.checkInConnection(conn);
        }
    }
}